<script setup lang="ts">
import { computed, onMounted, ref, h } from 'vue'
import { UploadOutlined, DownloadOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { sleep } from '@/views/file/utils'
import FileUpload from '@/views/File/FileUpload.vue'
import Request from '@/api/axios'
import { getDirName } from '@/utils/path'
type File = {
    path: string
    name: string
    size: number
    mode: string
    isDir: boolean
    ModTime: string
    children?: File[]
}
type RawFile = {
    Path: string
    Name: string
    Size: number
    Mode: string
    IsDir: boolean
    ModTime: string
}
const cloudStorage = ref<RawFile[]>([])
const cloudStorageDir = ref<File>()
const getNode = (path: string, node: File = cloudStorageDir.value as File) => {
    if (node.path === path) return node
    for (const child of node.children || []) {
        const p = getNode(path, child)
        if (p != undefined) return p
    }
    return undefined
}
const fetchCloudStorage = async () => {
    await Request.get({ url: '/cloud-storage' }).then((res) => {
        if (res.code === HttpStatusCode.Ok) {
            cloudStorage.value = res.info
            if (res.info && res.info.length === 0) return
            cloudStorageDir.value = {
                name: cloudStorage.value[0].Name,
                path: cloudStorage.value[0].Path,
                size: cloudStorage.value[0].Size,
                mode: cloudStorage.value[0].Mode,
                isDir: true,
                ModTime: cloudStorage.value[0].ModTime,
                children: []
            }
            for (let i = 1; i < cloudStorage.value.length; i++) {
                const file = cloudStorage.value[i]
                getNode(getDirName(file.Path)).children.push({
                    name: file.Name,
                    path: file.Path,
                    size: file.Size,
                    mode: file.Mode,
                    isDir: file.IsDir,
                    ModTime: file.ModTime,
                    children: []
                })
            }
        }
    })
}

onMounted(async () => {
    fetchCloudStorage()
})


const uploadList = ref<File[]>([])
type Directory = {
    filename: string
    files: {
        file: File
        path: string
        progress?: number
    }[]
}
const uploadDirectory = ref<Directory[]>([])
//TODO 保存上传的文件夹列表
const handleDragOver = (event: any) => {
    event.preventDefault()
}
const handleDrop = (event: any) => {
    event.preventDefault()
    for (const file of event.dataTransfer.items) {
        const entry = file.webkitGetAsEntry()
        if (entry.isDirectory) {
            const readDirecotry = (entry: any) => {
                if (entry.isDirectory) {
                    entry.createReader().readEntries((entries) => {
                        entries.forEach((entry) => {
                            if (entry.isFile) {
                                entry.file((f) => {
                                    uploadList.value.push(f)
                                })
                            } else readDirecotry(entry)
                        })
                    })
                }
            }
            readDirecotry(entry)
        } else entry.file((f) => uploadList.value.push(f))
    }
}

const uploading = ref(false)
const loadingFile = ref(false)
const finishCount = ref(0)
const handleFileChange = (event: any) => {
    loadingFile.value = false
    uploadList.value = [...uploadList.value, ...event.target.files]
}
const handleDirectoryChange = (event: any) => {
    const files = event.target.files
    for (let i = 0; i < files.length; i++) {
        const file = files[i]
        uploadList.value.push(file)
    }
}
const uploadok = () => {
    finishCount.value += 1
    if (finishCount.value === uploadList.value.length) {
        message.success('上传成功')
        sleep(1000).then(() => {
            uploadList.value = []
            uploading.value = false
            fetchCloudStorage()
        })
    }
}

const handleUpload = async () => {
    uploading.value = true
}
const chunkSize = ref(10) // 1MB
const handleDelete = (index: number) => {
    uploadList.value.splice(index, 1)
}
const handleCloundStorageDelete = async (key: string) => {
    const filename = key.split('/').filter(s => s).pop()
    await Request.get({ url: `/file/delete?filename=${filename}` }).then(res => {
        if (res.code === 200) {
            message.success('删除成功')
            fetchCloudStorage()
        }
    })
}
const expandedKeys = ref([])
const selectedKeys = ref([])
const MaptoTreeData = (data: File[]) => {
    if (!data) return []
    const mapdata = data.map((item) => {
        return {
            title: item.name,
            key: item.path,
            isLeaf: !item.isDir,
            size: item.size,
            name: item.name,
            children: item.children && item.children.length > 0 ? MaptoTreeData(item.children) : []
        }
    })
    return mapdata
}
const treeData = computed(() => {
    return MaptoTreeData(cloudStorageDir.value?.children || [])
})

import Downloader from '@/api/download'
import { HttpStatusCode } from 'axios'
const handleDownload = async () => {
    const nodeList = selectedKeys.value.map((key) =>
        treeData.value.find((item) => item.key === key)
    )
    await Promise.all(
        nodeList.map(async (node) => {
            await Downloader.DownloadFile(node.name, node.size)
        })
    )
}
const isDragover = ref(false)
</script>

<template>
    <a-spin :spinning="loadingFile">
        <div class="drag-file-upload" @dragover="handleDragOver" @drop="handleDrop" :class="{ 'dragover': isDragover }"
            @dragenter="isDragover = true" @dragleave="isDragover = false">
            <div class="upload-icon">
                <UploadOutlined />
            </div>
            <div class="upload-text">
                <h3>拖拽文件到此处上传</h3>
                <p>支持单个文件或整个文件夹</p>
            </div>

            <a-row :gutter="16" class="action-buttons">
                <a-col :span="12">
                    <input type="file" id="fileInput" style="display: none" multiple @click="loadingFile = true"
                        @cancel="loadingFile = false" @change="handleFileChange($event)" accept="*" />
                    <label for="fileInput" class="w-25 custom-btn">选择文件</label>
                </a-col>
                <a-col :span="12"><input type="file" id="directoryInput" style="display: none"
                        @click="loadingFile = true" @cancel="loadingFile = false" webkitdirectory mozdirectory
                        odirectory @change="handleDirectoryChange" />
                    <label for="directoryInput" class="custom-btn">选择文件夹</label>
                </a-col>
            </a-row>
            <br />
        </div>
    </a-spin>

    <a-row :gutter="24" class="main-content">
        <a-col :span="12" class="upload-section">
            <a-flex justify="center">
                <a-space>
                    <a-button :loading="uploading" :disabled="uploadList.length === 0" type="primary"
                        @click="handleUpload">上传</a-button>
                    <a-button type="dashed" danger @click="uploadList = []">清空</a-button>
                    <a-input-number v-model:value="chunkSize">
                        <template #addonAfter>MB</template>
                    </a-input-number>
                </a-space>
            </a-flex>
            <a-card title="待上传文件" class="file-list-card" :bordered="false">
                <div v-if="uploadList.length === 0" class="empty-tip">暂无待上传文件</div>
                <div v-else class="upload-list">
                    <div v-for="(file, index) in uploadList" :key="index" class="file-item">
                        <div class="file-meta">
                            <PaperClipOutlined class="file-icon" />
                            <div class="file-info">
                                <div class="file-name">{{ file.name }}</div>
                                <div class="file-size">{{ (file.size / 1024 / 1024).toFixed(2) }}MB</div>
                            </div>
                            <FileUpload :file="file" :upload="uploading" :chunkSize="chunkSize" @uploadok="uploadok"
                                @delete="handleDelete" />
                        </div>
                        <a-button danger size="small" @click="handleDelete(index)">
                            <template #icon>
                                <DeleteOutlined />
                            </template>
                        </a-button>
                    </div>
                </div>
            </a-card>
        </a-col>

        <!-- 右侧云存储目录 -->
        <a-col :span="12" class="cloud-section">
            <a-card title="云端存储" class="cloud-tree-card" :bordered="false">
                <a-directory-tree v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys" multiple
                    :tree-data="treeData" class="tree-container">
                    <template #title="{ key, title }">
                        <span>{{ title }}</span>
                        <a-button :icon="h(DeleteOutlined)" type="link" danger size="small"
                            @click.stop="handleCloundStorageDelete(key)">
                        </a-button>
                    </template>
                    <template #icon></template>
                    <!-- <template #icon="{ key, selected }"></template> -->
                </a-directory-tree>
                <a-button type="primary" @click="handleDownload" class="download-btn"
                    :disabled="selectedKeys.length === 0">
                    <DownloadOutlined />
                    下载选中项
                </a-button>
            </a-card>
        </a-col>
    </a-row>
</template>

<style scoped>
.drag-file-upload {
    height: 320px;
    width: 100%;
    max-width: 800px;
    border: 2px dashed #1890ff;
    border-radius: 16px;
    background: rgba(24, 144, 255, 0.05);
    margin: 2rem auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    position: relative;

    &.dragover {
        background: rgba(24, 144, 255, 0.1);
        border-color: #096dd9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
    }
}

.upload-icon {
    font-size: 3rem;
    color: #1890ff;
    margin-bottom: 1rem;
}

.upload-text {
    text-align: center;

    h3 {
        color: #1890ff;
        margin-bottom: 0.5rem;
    }

    p {
        color: #666;
        font-size: 0.9rem;
    }
}

.action-buttons {
    margin-top: 2rem;

    :deep(.ant-col) {
        display: flex;
        justify-content: center;
    }
}

.custom-btn {
    background: #1890ff;
    color: white;
    padding: 8px 16px;
    border-radius: 8px;
    border: none;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s ease;

    &:hover {
        background: #096dd9;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
    }
}

.custom-btn {
    background-color: #007bff;
    color: white;
    padding: 0.5rem 0.875rem;
    border-radius: 0.375rem;
    cursor: pointer;
    width: 6.25rem;
    transition: background-color 0.3s;
    display: inline-block;

    &:hover {
        background-color: #0062cc;
    }
}

.main-content {
    margin-top: 2rem;
}

.file-list-card,
.cloud-tree-card {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border-radius: 12px;
    margin-top: 24px;
}

.upload-list {
    max-height: 400px;
    overflow-y: auto;
}

.file-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    margin: 8px 0;
    background: rgba(24, 144, 255, 0.05);
    border-radius: 8px;
    /* transition: all 0.3s; */
}

/* .file-item:hover {
    transform: translateX(5px);
    background: rgba(24, 144, 255, 0.1);
} */

.file-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-grow: 1;
}

.file-info {
    display: flex;
    flex-direction: column;
}

.file-name {
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
    max-width: 300px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.file-size {
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
}

/* 新增树形控件样式 */
.tree-container {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    padding: 8px;
}

/* 修改树节点样式 */
:deep(.ant-tree-treenode) {
    padding: 8px 0;
    width: 100%;

    &:hover {
        background: rgba(24, 144, 255, 0.05);
        border-radius: 6px;
    }

    &.ant-tree-treenode-selected {
        background: rgba(24, 144, 255, 0.1) !important;
        border-radius: 6px;
    }
}

/* 调整展开图标 */
:deep(.ant-tree-switcher) {
    color: #1890ff;
    font-size: 16px;
    padding: 0 8px;

    &:hover {
        color: #096dd9;
    }
}

/* 节点文字样式 */
:deep(.ant-tree-node-content-wrapper) {
    flex: 1;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
    transition: all 0.2s;

    &:hover {
        color: #1890ff;
        background: transparent;
    }

    &::before {
        content: '📁';
        margin-right: 8px;
    }
}

/* 文件节点图标 */
:deep(.ant-tree-treenode-leaf) .ant-tree-node-content-wrapper::before {
    content: '📄';
}

.download-btn {
    margin-top: 16px;
    width: 100%;
    border-radius: 8px;
    background: linear-gradient(45deg, #1d90f5, #6dd5fa);
    border: none;
}

.empty-tip {
    text-align: center;
    color: rgba(0, 0, 0, 0.45);
    padding: 24px;
}
</style>
